package me.zk.practice1.s;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author zhangkai
 * @date 2023/8/4 14:27
 */
public class LS402 {

    public String removeKdigits(String num, int k) {
        Deque<Character> deque = new LinkedList<>();

        for (int i = 0; i < num.length(); i++) {
            Character ch = num.charAt(i);
            while (!deque.isEmpty() && k>0 && deque.peekLast() > ch) {
               deque.pollLast();
               k--;
            }
            deque.offerLast(ch);
        }
        //防止出现k未为0的情况
        for (int i = 0; i < k; i++) {
            deque.pollLast();
        }
        StringBuilder sb = new StringBuilder();
        boolean leadingZero = true;
        while (!deque.isEmpty()) {
            Character ch = deque.pollFirst();
            if (leadingZero && ch == '0') {
                continue;
            }
            leadingZero = false;
            sb.append(ch);
        }
        return sb.length() == 0 ? "0": sb.toString();

    }
}
